#include "printk.h"
#include "gate.h"
#include "trap.h"
#include "memory.h"
#include "lib.h"
#include "task.h"
#include "cpu.h"

#if APIC
#include "apic.h"
#else
#include "8259a.h"
#endif

#include "keyboard.h"
#include "mouse.h"
#include "disk.h"

void Start_Kernel(void) {
    g_pos.x_res = 1024;
    g_pos.y_res = 768;
    g_pos.x_pos = 0;
    g_pos.y_pos = 0;
    g_pos.x_char_size = 8;
    g_pos.y_char_size = 16;
    g_pos.FB_addr = (int *)0xffff800003000000;          // 帧缓存物理地址0xe0000000映射到0xffff800003000000和0xa00000处
    g_pos.FB_length = (g_pos.x_res * g_pos.y_res * 4 + PAGE_4K_SIZE - 1) & PAGE_4K_MASK;

    load_TR(10);

    set_tss64(_stack_start, _stack_start, _stack_start, 0xffff800000007c00, 0xffff800000007c00, 0xffff800000007c00, 0xffff800000007c00, 0xffff800000007c00, 0xffff800000007c00, 0xffff800000007c00);

    sys_vector_init();

    cpu_init();

    g_mem_mgmt.start_code = (unsigned long)&_text;
    g_mem_mgmt.end_code = (unsigned long)&_etext;
    g_mem_mgmt.end_data = (unsigned long)&_edata;
    g_mem_mgmt.end_brk = (unsigned long)&_end;

    color_printk(RED, BLACK, "memory init\n");
    memory_init();

    color_printk(RED, BLACK, "slab init\n");
    slab_init();

    color_printk(RED, BLACK, "frame buffer init \n");
	frame_buffer_init();
	color_printk(WHITE, BLACK, "frame_buffer_init() is OK \n");

    color_printk(RED, BLACK, "pagetable init \n");	
	pagetable_init();

    color_printk(RED, BLACK, "interrupt init\n");
#if APIC
    apic_ioapic_init();
#else
    pic_8259a_init();
#endif

    color_printk(RED, BLACK, "keyboard init\n");
    keyboard_init();

    color_printk(RED, BLACK, "mouse init\n");
    mouse_init();

    color_printk(RED, BLACK, "disk init\n");
    disk_init();

    // color_printk(RED, BLACK, "task init\n");
    // task_init();

    while (1) {
        if (g_p_kb->count) {
            analysis_keycode();
        }
        if (g_p_mouse->count) {
            analysis_mousecode();
        }
    }
}
